// pages/call/voice-call/voice-call.js
const httpUtils = require('../../../utils/httpUtil')
Page({

  data: {
    timer: null,
    seconds: 0,
    isMuted: false,
  },

  statechange(e) {
    console.log('live-pusher code:', e.detail.code)
  },

  onLoad() {
    this.startTimer();
    this.startRecordAudio();
  },

  onUnLoad() {
    this.clearTimer();
    
  },

  // 开始计时
  startTimer() {
    this.clearTimer();
    this.data.timer = setInterval(() => {
      this.data.seconds++;
      const minutes = Math.floor(this.data.seconds / 60).toString().padStart(2, '0');
      const seconds = (this.data.seconds % 60).toString().padStart(2, '0');
      this.setData({
        callTime: `${minutes}:${seconds}`
      });
    }, 1000);
  },

  // 清除计时器
  clearTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
  },

  toggleMute() {
    this.setData({
      isMuted: !this.data.isMuted
    })

  },

  onEndCallTap() {
    this.hangup();
  },

  hangup() {
    httpUtils.request({
      'method': 'POST',
      'url': '/prod-api/interface/hangUp',
      'showLoading': true,
      'message': '挂断中',
      'data': {
        'conferenceNumber': this.data.defaultConfNum
      }
    }).then(res=>{
      if (res.data.code == 200) {
        this.data.hangupSuccess = true;
      }
      wx.navigateBack();
    });
  },

  startRecordAudio() {
    const recorderManager = wx.getRecorderManager()

    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onPause(() => {
      console.log('recorder pause')
    })
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res
    })
    recorderManager.onFrameRecorded((res) => {
      const { frameBuffer } = res
      console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    })
    
    const options = {
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 44,
    }
    
    recorderManager.start(options)
  },
})